package com.bree.erp.service.stateless;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.ItemRequest;
import com.bree.erp.entity.MasterItem;
import com.bree.erp.entity.PartUnit;
import com.bree.erp.entity.PurchaseRequisition;
import com.bree.erp.entity.Unit;
import com.bree.erp.service.ItemRequestService;

@Stateless
public class ItemRequestServiceBean implements ItemRequestService {
	
	@PersistenceContext()
	private EntityManager em;
	
	public ItemRequestServiceBean() {
		
	}
	

	public ItemRequestServiceBean(EntityManager em) {
		this.em = em;
	}
	

	@Override
	public ItemRequest create(PurchaseRequisition purchaseRequisition,
			PartUnit partUnit, double quantity, String remarks) {
		
		ItemRequest itemRequest = new ItemRequest();
		
		itemRequest.setPurchaseRequisition(purchaseRequisition);
		itemRequest.setPartUnit(partUnit);
		itemRequest.setQuantity(quantity);
		itemRequest.setRemarks(remarks);
		
		em.persist(itemRequest);
		
		return itemRequest;
		
	}


	@Override
	public ItemRequest create(Long prId, Long puId, double quantity, String remarks) {

		PurchaseRequisition pr = em.find(PurchaseRequisition.class, prId);
		PartUnit pu = em.find(PartUnit.class, puId);
		
		return create(pr, pu, quantity, remarks);
		
	}

	@Override
	public ItemRequest read(long id) {
		
		return em.find(ItemRequest.class, id);
	}

	@Override
	public ItemRequest update(long id,	double quantity, String remarks) {
		
		ItemRequest itemRequest = read(id);
		
		itemRequest.setQuantity(quantity);
		itemRequest.setRemarks(remarks);
		
		return itemRequest;
	}

	@Override
	public void delete(long id) {

		ItemRequest itemRequest = read(id);
		
		itemRequest.setPurchaseRequisition(null);
		
		em.remove(itemRequest);
		
	}


	@Override
	public void delete(ItemRequest entity) {

		em.remove(entity);
		
	}


	@Override
	public List<ItemRequest> list(long parentId) {
		
		TypedQuery<ItemRequest> query = em.createNamedQuery(
				ItemRequest.QUERY_SELECT_ITEMREQUESTS_OF_PURCHASEREQUISITION, 
				ItemRequest.class).setParameter("parentId", parentId);
		
		return query.getResultList();
	}

}
